package com.lingfengerick.commons.encrypt.sm4tool;

import com.lingfengerick.commons.encrypt.sm4tool.toolkit.SM4Base;
import com.lingfengerick.commons.encrypt.sm4tool.toolkit.SM4_Context;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.util.Base64;

/**
 * @author lingfengerick
 * @since 2022/9/20 14:52
 */
@Data
public class CBCSecretStrategy extends SM4SecretStrategy{

    private String iv ="";

    /**
    * 使用CBC模式获取加密串
    * @author  lingfengerick
    * @since  2022/9/20  15:19
    * @param sm4Context sm4上下文
    * @param publicKey 密钥
    * @param dataStr 数据
    * @return 加密后数组
    *
    */
    @Override
    byte[] getEncryptedByte(SM4_Context sm4Context, String dataStr , String publicKey){
        byte[] ivBytes;
        SM4Base sm4 = null;
        byte[] encryptedBytes;
        try {
            byte[] keyBytes;
            if (HEX_STRING) {
                keyBytes = hexStringToBytes(publicKey);
                ivBytes = hexStringToBytes(getIv());
            } else {
                keyBytes = publicKey.getBytes();
                ivBytes = getIv().getBytes();
            }
            sm4 = new SM4Base();
            sm4.sm4_setkey_enc(sm4Context, keyBytes);
            encryptedBytes = sm4.sm4_crypt_cbc(sm4Context, ivBytes, dataStr.getBytes());
        } catch (Exception e) {
            return null;
        }
        return encryptedBytes;
    }

    /**
    * 解密
    * @author  lingfengerick
    * @since  2022/9/20  16:03
    * @param sm4Context sm4上下文
    * @param privateKey 密钥
    * @param encryptDataStr 加密数据
    * @return 解密数组
    *
    */
    @Override
    byte[] getDecryptedByte(SM4_Context sm4Context ,String encryptDataStr , String privateKey) {
        try {
            if (StringUtils.isEmpty(iv)){
                iv = "";
            }
            byte[] keyBytes;
            byte[] ivBytes;
            if (HEX_STRING) {
                keyBytes = hexStringToBytes(privateKey);
                ivBytes = hexStringToBytes(iv);
            } else {
                keyBytes = privateKey.getBytes();
                ivBytes = iv.getBytes();
            }
            SM4Base sm4 = new SM4Base();
            sm4.sm4_setkey_dec(sm4Context, keyBytes);
            return sm4.sm4_crypt_cbc(sm4Context, ivBytes, Base64.getDecoder().decode(encryptDataStr));
        } catch (Exception e) {
            return null;
        }
    }
}
